define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index     : () => {
            new Vue({
                el: "#taskIndex",
                data() {
                    return {
                        category_map  : [],
                        category_label: '',
                        allAjax       : true,
                        tableAjax     : false,
                        taskData      : [],
                        currentPage   : 1,
                        limit         : 10,
                        offset        : 0,
                        totalPage     : 0,
                        where         : {
                            category: ''
                        }
                    }
                },
                created() {
                    this.category_map = Config.category_map;
                },
                mounted() {
                    this.where.category = String(this.category_map[0].name);
                    this.category_label = String(this.category_map[0].label);
                },
                watch  : {
                    'where.category': {
                        handler(newV) {
                            this.limit = 10;
                            this.offset = 0;
                            this.getData();
                        }
                    }
                },
                methods: {
                    // 获取列表数据
                    getData() {
                        let that = this;
                        if (!that.allAjax) {
                            that.tableAjax = true;
                        }
                        Fast.api.ajax({
                            url    : 'health/website/task/index',
                            loading: false,
                            type   : 'GET',
                            data   : {
                                category: that.where.category,
                                limit   : that.limit,
                                offset  : that.offset
                            }
                        }, function (ret, res) {
                            that.taskData = ret.rows;
                            that.totalPage = ret.total;
                            that.allAjax = false;
                            that.tableAjax = false;
                            return false;
                        }, function (ret, res) {
                            that.allAjax = false;
                            that.tableAjax = false;
                        })
                    },
                    pageSizeChange(val) {
                        this.offset = 0;
                        this.currentPage = 1
                        this.limit = val;
                        this.getData();
                    },
                    pageCurrentChange(val) {
                        this.offset = (val - 1) * this.limit;
                        this.currentPage = val;
                        this.getData();
                    },
                    categoryTabClick(e) {
                        this.category_label = e.label;
                    },
                    //操作按钮
                    operation(opttype, id, status) {
                        let that = this;
                        switch (opttype) {
                            case 'del':
                                that.$confirm('此操作将删除任务, 是否继续?', '提示', {
                                    confirmButtonText: '确定',
                                    cancelButtonText : '取消',
                                    type             : 'warning'
                                }).then(() => {
                                    Fast.api.ajax({
                                        url    : 'health/website/task/del/ids/' + id,
                                        loading: false,
                                        type   : 'POST',
                                    }, function (ret, res) {
                                        that.getData()
                                    })
                                }).catch(() => {
                                });

                                break;
                            case 'status':
                                let str = status == 1 ? 0 : 1;
                                that.$confirm('此操作将修改任务图状态, 是否继续?', '提示', {
                                    confirmButtonText: '确定',
                                    cancelButtonText : '取消',
                                    type             : 'warning'
                                }).then(() => {
                                    Fast.api.ajax({
                                        url    : `health/website/task/setStatus/ids/${id}/status/${str}`,
                                        loading: false,
                                    }, function (ret, res) {
                                        that.getData();
                                    })
                                }).catch(() => {
                                });
                                break;
                            case 'create':
                                Fast.api.open("health/website/task/add?category=" + that.where.category, "创建" + this.category_label, {
                                    callback(data) {
                                        if (data.data) {
                                            that.getData();
                                        }
                                    }
                                });
                                break;
                            case 'edit':
                                Fast.api.open("health/website/task/edit?ids=" + id, "编辑任务", {
                                    callback(data) {
                                        if (data.data) {
                                            that.getData();
                                        }
                                    }
                                });
                                break;
                        }
                    },
                }
            })
        },
        add       : function () {
            Controller.detailInit('add');
        },
        edit      : function () {
            Controller.detailInit('edit');
        },
        detailInit: function (type) {
            function urlParmas(par) {
                let value = ""
                window.location.search.replace("?", '').split("&").forEach(i => {
                    if (i.split('=')[0] == par) {
                        value = JSON.parse(decodeURI(i.split('=')[1]))
                    }
                })
                return value
            }

            var detailInit = new Vue({
                el: "#detailInit",
                data() {
                    return {
                        optType         : type,
                        id              : urlParmas('ids'),
                        detailForm      : {},
                        detailFormInit  : {
                            name                : '',
                            description         : '',
                            complete_num        : 1,
                            award_type          : 1,
                            award_value         : 0,
                            complete_way        : '',
                            complete_way_content: {duration: '', video_id: ''},
                            status              : 1,
                        },
                        award_type_map  : [],
                        complete_way_map: [],
                        //完成方式数据
                        complete_way: {
                            //完成方式规则
                            rule: {
                                complete_num: 0
                            },
                            //视频列表
                            video_list: [],
                        },
                        rules       : {
                            name        : [{
                                required: true,
                                message : '请输入任务名称',
                                trigger : 'blur'
                            }],
                            description : [{
                                required: true,
                                message : '请输入任务描述',
                                trigger : 'blur'
                            }],
                            complete_num: [{
                                required: true,
                                message : '请输入完成次数',
                                trigger : 'blur'
                            }],
                            award_type  : [{
                                required: true,
                                message : '请选择奖励类型',
                                trigger : 'blur'
                            }],
                            complete_way: [{
                                required: true,
                                message : '请选择完成方式',
                                trigger : 'blur'
                            }],
                        }

                    }
                },
                created() {
                    this.award_type_map = Config.award_type_map || [];
                    this.complete_way_map = Config.complete_way_map || [];
                    this.detailForm = JSON.parse(JSON.stringify(this.detailFormInit));
                    if (this.optType == 'edit') {
                        for (key in this.detailForm) {
                            this.detailForm[key] = Config.row[key]
                        }
                    } else {
                        if (Config.category) {
                            this.detailForm.category = Config.category;
                        }
                    }
                },
                computed: {
                    selectVideoObj() {
                        let that = this;
                        return this.complete_way.video_list.find((item) => {
                            return item.id == that.detailForm.complete_way_content.video_id;
                        })
                    }
                },
                watch   : {
                    'detailForm.complete_way': {
                        handler(newVal) {
                            if (newVal) {
                                let completeWay = this.complete_way_map.find(function (item, index) {
                                    return newVal === item.name;
                                });
                                this.complete_way.rule = completeWay.rule || {};
                                if (completeWay.rule.complete_num > 0) {
                                    this.detailForm.complete_num = completeWay.rule.complete_num
                                }
                                switch (newVal) {
                                    case 1:
                                        this.getVideo()
                                        break;
                                }
                            }
                        },
                        immediate: true
                    },
                    'selectVideoObj'         : {
                        handler(newVal) {
                            if (!this.detailForm.complete_way_content.duration || this.detailForm.complete_way_content.duration > newVal.duration) {
                                this.detailForm.complete_way_content.duration = newVal.duration;
                            }
                        },
                    }
                },
                methods : {
                    // 获取视频列表
                    getVideo() {
                        let that = this;
                        Fast.api.ajax({
                            url    : 'health/website/task/video_lists',
                            loading: false,
                        }, function (ret, res) {
                            that.complete_way.video_list = res.data;
                            return false;
                        })
                    },
                    addImg(type, index, multiple) {
                        let that = this;
                        parent.Fast.api.open("general/attachment/select?multiple=" + multiple, "选择图片", {
                            callback: function (data) {
                                that.detailForm.image = data.url;
                            }
                        });
                        return false;
                    },
                    delImg(type, index) {
                        this.detailForm.image = ''
                    },
                    submitForm(type, formName) {
                        let that = this;
                        if (type) {
                            this.$refs[formName].validate((valid) => {
                                if (valid) {
                                    let formData = JSON.stringify(that.detailForm);
                                    if (that.optType == 'edit') {
                                        Fast.api.ajax({
                                            url    : 'health/website/task/edit/ids/' + that.id,
                                            loading: true,
                                            data   : {
                                                data: formData
                                            }
                                        }, function (ret, res) {
                                            Fast.api.close({data: true});
                                        })
                                    } else {
                                        Fast.api.ajax({
                                            url    : 'health/website/task/add',
                                            loading: true,
                                            data   : {
                                                data: formData
                                            }
                                        }, function (ret, res) {
                                            Fast.api.close({data: true});
                                        })
                                    }
                                } else {
                                    return false;
                                }
                            });
                        } else {
                            Fast.api.close({data: false});
                        }
                    },
                },
            })
        },
    }
    return Controller;
});